package IOTWeb.com.agreementclient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.commons.lang.StringUtils;

public class TcpClient {
    /*
       创建客户端
     */
    public static void main(String[] args) throws IOException {

        //创建客户端Socket,创建时3次握手建立,连接
        Socket socket = new Socket("127.0.0.1",24992);
        /*
          这里需要抛出一个IOException
        */

        //客户端向服务器发送信息
        OutputStream out = socket.getOutputStream();
        out.write("你好服务器".getBytes("utf-8"));

        //接收服务器端发送的信息
        InputStream in = socket.getInputStream();
        byte[] bytes = new byte[100];
        int len = in.read(bytes);
        System.out.println(new String(bytes,0,len,"utf-8"));
    }


    /**
     * 将十六进制的字符串转换成字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStrToByteArrs(String hexString) {
        if (StringUtils.isEmpty(hexString)) {
            return null;
        }

        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        int index = 0;

        byte[] bytes = new byte[len / 2];

        while (index < len) {
            String sub = hexString.substring(index, index + 2);
            bytes[index / 2] = (byte) Integer.parseInt(sub, 16);
            index += 2;
        }

        return bytes;
    }

    /**
     * 数组转换成十六进制字符串
     * 
     * @param byte[]
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
            // 在这里故意追加一个逗号便于最后的区分
            sb.append(" ");
        }
        return sb.toString();
    }

//    public static void main(String[] args) {
//        System.out.println(sendCmd("0f 0f"));
//        System.out.println(sendCmd("0f 0f"));
//    }
}
